package com.ugoodtech.mdcc.web.service.impl;

import com.mysema.query.BooleanBuilder;
import com.ugoodtech.mdcc.core.Constants;
import com.ugoodtech.mdcc.core.domain.*;
import com.ugoodtech.mdcc.core.dto.ComplaintSearch;
import com.ugoodtech.mdcc.core.dto.ComplaintTimeResponse;
import com.ugoodtech.mdcc.core.repository.*;
import com.ugoodtech.mdcc.core.service.ComplaintSearchService;
import com.ugoodtech.mdcc.core.service.ComplaintTimeService;
import com.ugoodtech.mdcc.core.service.GetDepartmentNameForSendService;
import com.ugoodtech.mdcc.core.service.WechatService;
import com.ugoodtech.mdcc.core.utils.ComplaintReportUtil;
import com.ugoodtech.mdcc.web.dto.ComplaintResponse;
import com.ugoodtech.mdcc.web.dto.JsonResponse;
import com.ugoodtech.mdcc.web.service.ComplaintReportService;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestParam;

import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class ComplaintReportServiceImpl implements ComplaintReportService {

    @Autowired
    private ComplaintSearchService complaintSearchService;

    @Autowired
    private ComplaintUserRepository complaintUserRepository;

    @Autowired
    private UserProfileRepository userProfileRepository;

    @Autowired
    private ComplaintReportDataRepository complaintReportDataRepository;

    @Autowired
    private StationRepository stationRepository;

    @Autowired
    private QuestionRepository questionRepository;

    @Autowired
    private ComplaintSolutionReportRepository complaintSolutionReportRepository;

    @Autowired
    private ComplaintReportRepository complaintReportRepository;

    @Autowired
    private WechatService wechatService;

    @Autowired
    private ComplaintTimeService complaintTimeService;

    @Autowired
    private GetDepartmentNameForSendService getDepartmentNameForSendService;


    /**
     * 编辑投诉报告
     *
     * @param complaintReportId
     * @param questionId
     * @param answerId
     * @param answerOther
     * @return
     */
    @Override
    public JsonResponse editComplaintReport(Long complaintReportId, Long questionId, String answerId, String answerOther) {
        Question question = questionRepository.findOne(questionId);
        if (null == question) {
            return JsonResponse.errorResponseWithError("抱歉", "未找到此题");
        }
        ComplaintReportData complaintReportData = complaintReportDataRepository.selectByQuestion(complaintReportId, questionId);
        if (null == complaintReportData) {
            return JsonResponse.errorResponseWithError("抱歉", "未找到此题");
        }
        if (StringUtils.isNotEmpty(answerId)) {
            complaintReportData.setAnswerId(answerId);
        }
        if (StringUtils.isNotEmpty(answerOther)) {
            complaintReportData.setAnswerOther(answerOther);
        }
        if (questionId == 192L) {
            String stationName = updateEditComplaintReport(answerOther);
            if (StringUtils.isNotEmpty(stationName)) {
                ComplaintReportData complaintReportDataStationName = complaintReportDataRepository.selectByQuestion(complaintReportId, 193L);
                complaintReportDataStationName.setAnswerOther(stationName);
                complaintReportDataStationName.setUpdateTime(new Date());
                complaintReportDataRepository.save(complaintReportDataStationName);
            }
        }
        complaintReportData.setUpdateTime(new Date());
        complaintReportDataRepository.save(complaintReportData);
        return JsonResponse.successResponse();
    }


    private String updateEditComplaintReport(String answerOther) {
        Station station = stationRepository.findByStationNum(answerOther);
        if (null != station && StringUtils.isNotEmpty(station.getName())) {
            return station.getName();
        }
        return "";
    }


    /**
     * 查询投诉单
     *
     * @param pageable
     * @param complaintSearch
     * @return
     */
    @Override
    public JsonResponse getComplaintReport(Pageable pageable, ComplaintSearch complaintSearch, User clientUser) {
        List<Long> complaintIds = complaintSearchService.searchComplaintReport(complaintSearch, clientUser);
        if (complaintIds.isEmpty()) {
            return JsonResponse.successResponse();
        }
        BooleanBuilder builder = new BooleanBuilder();
        QComplaintUser qComplaintUser = QComplaintUser.complaintUser;
        builder.and(qComplaintUser.complaintReport.id.in(complaintIds));
        Sort sort = new Sort(Sort.Direction.DESC, "complaintReport.id", "updateTime");
        pageable = new PageRequest(pageable.getPageNumber(), pageable.getPageSize(), sort);
        Page<ComplaintUser> complaintReportList = complaintUserRepository.findAll(builder, pageable);
        List<ComplaintResponse> responseList = getUserResponse(complaintReportList.getContent());
        Page<ComplaintResponse> page = new PageImpl(responseList, pageable, complaintReportList.getTotalElements());
        return JsonResponse.successResponseWithPageData(page);
    }

    /**
     * 点击发送微信推送
     *
     * @param reportId
     * @param userIds
     * @return
     */
    @Override
    public JsonResponse sendComplaintReportMsg(Long reportId, String userIds) {
        ComplaintReport complaintReport = complaintReportRepository.findOne(reportId);
        if (null == complaintReport) {
            return JsonResponse.errorResponseWithError("抱歉", "未找到该投诉报告");
        }
        User nameUser = complaintReport.getUser();
        if (nameUser == null) {
            return JsonResponse.errorResponseWithError("抱歉", "未找到此报告的创建人");
        }
        UserProfile userProfile = userProfileRepository.findByUserId(nameUser.getId());
        if (userProfile == null || StringUtils.isEmpty(userProfile.getRealName())) {
            return JsonResponse.errorResponseWithError("抱歉", "未找到此报告的创建人信息");
        }
        String[] ids = userIds.split(",");
        StringBuffer userBuffer = new StringBuffer("");
        List<User> userList = new ArrayList<>();
        for (String id : ids) {
            if (StringUtils.isNotEmpty(id)) {
                UserProfile telephoneUser = userProfileRepository.findByUserId(Long.valueOf(id));
                if (telephoneUser != null && StringUtils.isNotEmpty(telephoneUser.getTelephone())) {
                    userBuffer.append(telephoneUser.getTelephone() + ",");
                    userList.add(telephoneUser.getUser());
                }
            }
        }
        String createTimeStr = complaintReport.getCreationTimeStr();
        String customer = "客户";
        ComplaintReportData complaintReportData = complaintReportDataRepository.selectByQuestion(complaintReport.getId(), 187L);
        if (null != complaintReportData && StringUtils.isNotEmpty(complaintReportData.getAnswerOther())) {
            createTimeStr = complaintReportData.getAnswerOther();
        }
        complaintReportData = complaintReportDataRepository.selectByQuestion(complaintReport.getId(), 193L);
        if (null != complaintReportData && StringUtils.isNotEmpty(complaintReportData.getAnswerOther())) {
            customer = complaintReportData.getAnswerOther();
        }
        String createUser = getDepartmentNameForSendService.getUserDepartmentName(nameUser);
        String firstData = "您好，" + createUser + "在" + createTimeStr + "提交的" + customer + "的投诉报告未处理完成。";
        String keyWord1 = ComplaintReportUtil.getReportStatus(complaintReport.getReportStatus());

        SimpleDateFormat simpleDateFormat = new SimpleDateFormat(Constants.DATE_TIME_FORMAT);
        String keyWord2 = simpleDateFormat.format(complaintReport.getSolutionTime());
        for (User weChatUser : userList) {
            wechatService.pushWechatMessage(weChatUser, "K8RDODMnerc2Orj7gbgTYKbalKDRqrJNyX6-s46OUc8", Constants.WECHAT_PUSH_URL, firstData,
                    "请尽快登录漆星服务系统进行处理。", keyWord1, keyWord2, "", "", "");
        }
        return JsonResponse.successResponse();
    }

    private List<ComplaintResponse> getUserResponse(List<ComplaintUser> complaintReportList) {
        List<ComplaintResponse> responseList = new ArrayList<>();
        for (ComplaintUser report : complaintReportList) {
            ComplaintResponse response = new ComplaintResponse();
            response.setId(report.getComplaintReport().getId());
            response.setTime(report.getComplaintReport().getUpdateTimeStr());
            response.setType(ComplaintReportUtil.getReportStatus(report.getComplaintReport().getReportStatus()));
            if (null != report.getUser()) {
                UserProfile userProfile = userProfileRepository.findByUserId(report.getUser().getId());
                response.setUserName(userProfile.getRealName());
            }
            ComplaintTimeResponse timeResponse = complaintTimeService.getComplaintTime(report.getComplaintReport());
            response.setActualTime(timeResponse.getTotalTime());
            response.setTimeRemaining(timeResponse.getRemainingTime());
            response.setActualProcessingTime(timeResponse.getActualProcessingTime());
            ComplaintReportData reportData = complaintReportDataRepository.selectByQuestion(report.getComplaintReport().getId(), 193L);
            if (null != reportData && StringUtils.isNotEmpty(reportData.getAnswerOther())) {
                response.setCustomerName(getComplaintReportCustomer(report.getComplaintReport().getId()));
            }
            Long solutionId = report.getComplaintReport().getSolutionId();
            if (null != solutionId) {
                ComplaintSolutionReport complaintSolutionReport = complaintSolutionReportRepository.findOne(solutionId);
                if (null != complaintSolutionReport) {
                    response.setSolutionTime(complaintSolutionReport.getCreationTimeStr());
                }
            }
            ComplaintReportData complaintReportData = complaintReportDataRepository.selectByQuestion(report.getComplaintReport().getId(), 187L);
            if (null != complaintReportData && StringUtils.isNotEmpty(complaintReportData.getAnswerOther())) {
                response.setCreateTime(complaintReportData.getAnswerOther());
            } else {
                response.setCreateTime(report.getComplaintReport().getUpdateTimeStr());
            }
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat(Constants.DATE_TIME_FORMAT);
            if (null != report.getComplaintReport().getAuditTime()) {
                String auditTime = simpleDateFormat.format(report.getComplaintReport().getAuditTime());
                response.setTime(auditTime);
            } else if (null != report.getComplaintReport().getFirstAuditTime()) {
                String auditTime = simpleDateFormat.format(report.getComplaintReport().getFirstAuditTime());
                response.setTime(auditTime);
            }
            reportData = complaintReportDataRepository.selectByQuestion(report.getComplaintReport().getId(), 192L);
            if (null != reportData && StringUtils.isNotEmpty(reportData.getAnswerOther())) {
                response.setVstarCode(reportData.getAnswerOther());
                Station station = stationRepository.findByStationNum(reportData.getAnswerOther());
                if (null != station && StringUtils.isNotEmpty(station.getName())) {
                    response.setCustomerName(station.getName());
                }
            }
            responseList.add(response);
        }
        return responseList;
    }

    public String getComplaintReportCustomer(Long complaintReportId) {
        ComplaintReportData reportData = complaintReportDataRepository.selectByQuestion(complaintReportId, 193L);
        String customerName = "";
        if (null != reportData && StringUtils.isNotEmpty(reportData.getAnswerOther())) {
            customerName = reportData.getAnswerOther();
        }
        reportData = complaintReportDataRepository.selectByQuestion(complaintReportId, 192L);
        if (null != reportData && StringUtils.isNotEmpty(reportData.getAnswerOther())) {
            Station station = stationRepository.findByStationNum(reportData.getAnswerOther());
            if (null != station && StringUtils.isNotEmpty(station.getName())) {
                return station.getName();
            }
        }
        return customerName;
    }


}
